
const db = require('db');
const { getTokenInfo } = require('tools/token');
const { toInsert } = require('tools/sqlString');

module.exports = async ctx => {
    const { connection, run } = db.init();
    await run('BEGIN'); // 开始事务
    try {
        await checkOrderNo(ctx, run);
        await into(ctx, run);
        await run('COMMIT');
        ctx.body = '{}';
        ctx.status = 200;
    } catch (error) {
        await run('ROLLBACK');
        ctx.body = error;
        ctx.status = 500;
    }
    connection.end();
}

/** 校验 orderNo 是否重复 */
async function checkOrderNo(ctx, run) {
    const orderNo = ctx.request.body.orderNo;
    const sqlStr = `SELECT orderNo FROM orders WHERE orderNo = '${orderNo}'`;
    const result = await run(sqlStr);
    if (result.err) {
        throw result.err
    }
    if (result.rows.length) {
        throw { message: '订单号重复' }
    }
}

/** 保存数据 */
async function into(ctx, run) {
    const body = ctx.request.body;
    const userInfo = getTokenInfo(ctx.header.authorization).userInfo;
    const sqlStr = `INSERT INTO orders ${toInsert({
        ...body,
        orderStatus: '1',
        commercialSpecialistId: userInfo.userid,
        commercialSpecialistName: userInfo.name,
        commercialSpecialistEmail: userInfo.email,
    }, {
        orderTime: 'now()',
    }, 'orders')}`;

    const result = await run(sqlStr)
    if (result.err) {
        throw result.err
    }
}

// async function getId(run) {
//     let result = await run('SELECT LAST_INSERT_ID() as id');
//     if (result.err) {
//         throw result.err
//     }
//     return result.rows[0].id;
// }
